package vip.xiaonuo.core;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.*;
import java.util.Date;
import java.util.List;

public class CSVUtil {
 
    /**
     * 导出
     */
    public static void exportCsv() throws IOException {
        File file =new File("D:/CSV");
        //判断路径是否存在，不存在则创建
        if(!file.exists()){
            file.mkdirs();
        }
        Appendable printWriter = new PrintWriter(file+"/wangs.csv","GBK");
        CSVPrinter csvPrinter = CSVFormat.EXCEL.withHeader("姓名", "性别", "年龄", "生日").print(printWriter);
        for (int i = 0; i < 10; i++) {
            csvPrinter.printRecord("lcf" + i, "M" + i, 18 + i, new Date());
        }
        csvPrinter.flush();
        csvPrinter.close();
    }
 
    public static void importCsv()throws IOException{
        InputStream inputStream =new FileInputStream("D:/CSV/导入.csv");//指定导入文件
        InputStreamReader inputStreamReader =new InputStreamReader(inputStream,"GBK");
        Reader reader = new BufferedReader(inputStreamReader);
        //指定csv的标题头
        CSVParser csvParser =CSVFormat.EXCEL.withHeader("name","sex","age","birthday").parse(reader);
 
        //将每一行记录存入list中
        List<CSVRecord> list = csvParser.getRecords();
 
        //变量循环list
       for(int i=0;i<list.size();i++){
           System.out.println(list.get(i).get("name")+":"+list.get(i).get("sex")+":"+list.get(i).get("age")+":"+list.get(i).get("birthday"));
       }
    }
 
    public static void main(String[] args) {
        try {
            CSVUtil.exportCsv();
            CSVUtil.importCsv();
        }catch (Exception e){
 
        }
    }
}
